package com.zqweb.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zqweb.common.constant.ProductConstant;
import com.zqweb.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.zqweb.gulimall.product.dao.AttrGroupDao;
import com.zqweb.gulimall.product.dao.CategoryDao;
import com.zqweb.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.zqweb.gulimall.product.entity.AttrGroupEntity;
import com.zqweb.gulimall.product.entity.CategoryEntity;
import com.zqweb.gulimall.product.service.CategoryService;
import com.zqweb.gulimall.product.vo.AttrRelationVo;
import com.zqweb.gulimall.product.vo.AttrRespVo;
import com.zqweb.gulimall.product.vo.AttrVo;
import java.util.Arrays;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zqweb.common.utils.PageUtils;
import com.zqweb.common.utils.Query;

import com.zqweb.gulimall.product.dao.AttrDao;
import com.zqweb.gulimall.product.entity.AttrEntity;
import com.zqweb.gulimall.product.service.AttrService;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrDao attrDao;

    @Override
    // 携带参数key的查询以及是否带cateId的条件查询
    public PageUtils baseQueryPage(Map<String, Object> params, Long cateId,String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)? ProductConstant.ProductParam.PARAM_BASE_TYPE.getCode() : ProductConstant.ProductParam.PARAM_SALE_TYPE.getCode());
        if(cateId != 0){
            queryWrapper.eq("catelog_id",cateId);
        }
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(wrap ->{
                wrap.like("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        /*
         由于分页查询后进行数据渲染时，渲染字段会比AttrEntity多出分组名和分类名的字段
         重新定义1个AttrRespVo，定义好这两个字段，将原先查到的每个AttrEntity进行流式处理
         重新封装成AttrRespVo，再把每个AttrRespVo装入1个List中，进行返回
          */
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVos = records.stream().map(attrEntity -> {
            // 定义1个attrRespVo，用于封装这额外的两个信息
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity,attrRespVo);

            // 查询每个attrEntity对应的分组名
            if(attrEntity.getAttrType() == ProductConstant.ProductParam.PARAM_BASE_TYPE.getCode()){
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId()));

                // 某些attr_id没有关联attrGroup_id，需要加上非空判断，防止空指针
                if(relationEntity != null && relationEntity.getAttrGroupId() != null){
                    AttrGroupEntity groupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(groupEntity.getAttrGroupName());
                }
            }

            // 查询每个attrEntity对应的分类名
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            // 某些attr_id没有关联category_id，需要加上非空判断，防止空指针
            if(categoryEntity != null){
                attrRespVo.setCatelogName(categoryEntity.getName());
            }

            return attrRespVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getByIdWithDetails(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        // 设置分组信息
        if(attrEntity.getAttrType() == ProductConstant.ProductParam.PARAM_BASE_TYPE.getCode()){
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrId));
            if(relationEntity != null && relationEntity.getAttrGroupId() != null){
                AttrGroupEntity groupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if(groupEntity != null){
                    attrRespVo.setAttrGroupId(groupEntity.getAttrGroupId());
                    attrRespVo.setGroupName(groupEntity.getAttrGroupName());
                }
            }
        }

        // 设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity != null){
            attrRespVo.setCatelogName(categoryEntity.getName());
            Long[] catelogPath = categoryService.getCatelogPath(catelogId);
            attrRespVo.setCatelogPath(catelogPath);
        }
        return attrRespVo;
    }

    @Override
    public void updateDetailsById(AttrVo attr) {
        Long attrId = attr.getAttrId();
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        // 添加或更新关联分组信息
        if(attr.getAttrGroupId() != null && attrEntity.getAttrType() == ProductConstant.ProductParam.PARAM_BASE_TYPE.getCode()){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrId);
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            // 查看一下原本该attrId是否关联了相应的attrGroup
            int count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id",attrId));
            if(count > 0){
                attrAttrgroupRelationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id",attrId));
            }else{
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }

    }

    @Override
    public void deleteRelations(AttrRelationVo[] relationVos) {
        List<AttrAttrgroupRelationEntity> relationEntities = Arrays.asList(relationVos).stream().map(relationVo -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(relationVo, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteRelations(relationEntities);
    }

    @Override
    public PageUtils listNoRelation(Map<String, Object> params, Long groupId) {
        /*
            先通过attrGroupDao查询出该groupId关联的分类id，再通过attrGroupDao查询出该分类id
            关联的所有attrGroup。然后通过attrattrGroupDao查询出这所有attrGroup关联的attr
            最后通过attrDao查询出该分类id下所有attrId不在上述所有attrGroup关联的attrIds中的attrId
            即为可新增的attrEntity
            最后添加些key的过滤查询以及分页展示
         */
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(groupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds = groupEntities.stream().map(groupEntity -> groupEntity.getAttrGroupId()).collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id", groupIds));
        List<Long> attrIds = null;
        if(relationEntities != null && relationEntities.size() > 0){
            attrIds = relationEntities.stream().map(relationEntity -> relationEntity.getAttrId()).collect(Collectors.toList());
        }
        QueryWrapper<AttrEntity> queryWrapper = null;
        if(attrIds != null && attrIds.size() > 0){
            queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId)
                    // 由于是要给分组新增属性，建立属性分组relation，所以需要判断属性是否为基本属性
                    .eq("attr_type", ProductConstant.ProductParam.PARAM_BASE_TYPE).notIn("attr_id", attrIds);
        }
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(obj ->{
                obj.like("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<Long> getSearchAttrIds(List<Long> attrIds) {
        List<Long> searchIds = attrDao.getSearchAttrIds(attrIds);
        return searchIds;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    @Override
    // 新增规格参数时，不仅需要往Attr这张表添加记录，同样也需要往AttrAttrgroupRelation关联表中添加记录
    public void saveDetail(AttrVo attrVo) {
        // 将attrVo的所有属性值通过映射关系一一拷贝到attrEntity
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.save(attrEntity);// 先保存规格参数表记录

        if(attrVo.getAttrGroupId() != null && attrEntity.getAttrType() == ProductConstant.ProductParam.PARAM_BASE_TYPE.getCode()){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            // 注意：这里要调用attrEntity对象，否则attrId为null（主键自增问题）
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            // 再往关联表中插入新记录
            attrAttrgroupRelationDao.insert(relationEntity);
        }

    }
}